import {
	fileURLToPath,
	URL
} from 'node:url'

import {
	defineConfig
} from 'vite'
import vue from '@vitejs/plugin-vue'
import {
	nodePolyfills
} from 'vite-plugin-node-polyfills'
import viteCompression from 'vite-plugin-compression' // 引入压缩插件

const host = process.env.TAURI_DEV_HOST;

// https://vite.dev/config/
export default defineConfig({
	base: './', // 关键修复！强制使用相对路径
	// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
	//
	// 1. prevent vite from obscuring rust errors
	// clearScreen: false,
	// 2. tauri expects a fixed port, fail if that port is not available
	plugins: [
		vue(),
		nodePolyfills({
			include: ['ws']
		}),
		// 配置压缩插件
		viteCompression({
			algorithm: 'gzip', // 可选 gzip 或 brotli
			ext: '.gz', // 压缩文件后缀
			threshold: 10240, // 超过 10KB 才压缩
			deleteOriginFile: false, // 是否删除源文件
			verbose: true // 显示压缩日志
		}),
	],
	css: {
		preprocessorOptions: {
			less: {
				charset: false,
			}
		}
	},
	resolve: {
		alias: {
			'@': fileURLToPath(new URL('./src', import.meta.url))
		},
	},
	server: {
		port: 50406, // 随机端口
		open: true,
		strictPort: true,
		host: host || false,
		hmr: host ?
			{
				protocol: "ws",
				host,
				port: 50408,
			} :
			undefined,
		watch: {
			// 3. tell vite to ignore watching `src-tauri`
			ignored: ["**/src-tauri/**"],
		},
		proxy: {
			"/api": {
				target: "http://localhost:50407",
				changeOrigin: true, // 必需
				secure: false, // 关闭SSL验证（适合本地https）
				rewrite: (path) => path.replace(/^\/api/, ""), // 路径重写
			}
		},
	}
})